package com.ruoyi.common.utils.ip;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import cn.hutool.http.HttpUtil;

/**
 * 获取地址类
 * 
 * @author ruoyi
 */
public class AddressUtils
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    // IP地址查询
    private static final String IP_URL = "https://ipcity.market.alicloudapi.com/ip/city/query";
    
    // 坐标查询
    private static final String LOCATION_URL = "https://apis.map.qq.com/ws/geocoder/v1/";
    
    /**
     * 腾讯地图密钥
     */
    private static final String IP_KEY = "5f305b6a0eb8473a82df9387c0b78950";
    
    /**
     * 上海市维度
     */
    private static final String LAT = "31.230416";
    /**
     * 上海市经度
     */
    private static final String LNG = "121.473701";

    // 未知地址
    private static final String UNKNOWN = "上海";

    public static String getRealAddressByIP(String ip){
        // 内网不查询
        if (IpUtils.internalIp(ip)){
            return "内网IP";
        }
        if (RuoYiConfig.isAddressEnabled()){
            try{
            	Map<String,Object> paramMap = new HashMap<>();
        		paramMap.put("key", IP_KEY);
        		paramMap.put("ip", ip);
        		String rspStr = HttpUtil.get(IP_URL, paramMap);
                if (StringUtils.isEmpty(rspStr)){
                    log.error("获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                JSONObject obj = JSON.parseObject(rspStr).getJSONObject("result").getJSONObject("ad_info");
                String region = obj.getString("province");
                String city = obj.getString("city");
                return String.format("%s %s", region, city);
            }
            catch (Exception e){
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return UNKNOWN;
    }
    
    /**
     * 通过坐标获取位置
     * @return
     */
    public static Address getAddressByLocation2(String lat,String lng){
    	Address address = new Address();
    	address.setLat(LAT);
    	address.setLng(LNG);
    	address.setProvince(UNKNOWN);
    	address.setCity(UNKNOWN);
    	address.setDistrict(UNKNOWN);
        // 内网不查询
        if (StringUtils.isBlank(lat) || StringUtils.isBlank(lng)){
            return address;
        }
        try{
        	Map<String,Object> paramMap = new HashMap<>();
    		paramMap.put("key", IP_KEY);
    		paramMap.put("location", lat+","+lng);
    		String rspStr = HttpUtil.get(LOCATION_URL, paramMap);
    		log.info("ip:"+rspStr);
    		System.out.println(rspStr);
            if (StringUtils.isEmpty(rspStr)){
                return address;
            }
            JSONObject result = JSON.parseObject(rspStr).getJSONObject("result");
            JSONObject adInfo = result.getJSONObject("ad_info");
            String province = adInfo.getString("province");
            String city = adInfo.getString("city");
            String district = adInfo.getString("district");
            address.setLat(lat);
            address.setLng(lng);
            address.setProvince(province);
            address.setCity(city);
            address.setDistrict(district);
            return address;
        }
        catch (Exception e){
            log.error("获取地理位置异常 ");
        }
        return address;
    }
    
    /**
     * 通过ip获取定位
     * @return
     */
    public static Address getAddressByIP(){
    	String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
    	Address address = new Address();
    	address.setLat(LAT);
    	address.setLng(LNG);
    	address.setProvince(UNKNOWN);
    	address.setCity(UNKNOWN);
        // 内网不查询
        if (IpUtils.internalIp(ip)){
            return address;
        }
        try{
        	Map<String, String> headers = new HashMap<String, String>();
    	    headers.put("Authorization", "APPCODE " + IP_KEY);
        	Map<String,Object> paramMap = new HashMap<>();
    		paramMap.put("ip", ip);
    		String rspStr = HttpUtil.createGet(IP_URL).addHeaders(headers).form(paramMap).execute().body();
    		log.info("ip:"+rspStr);
    		System.out.println(rspStr);
            if (StringUtils.isEmpty(rspStr)){
                log.error("获取地理位置异常 {}", ip);
                return address;
            }
            JSONObject data = JSON.parseObject(rspStr).getJSONObject("data");
            JSONObject result = data.getJSONObject("result");
            String lat = result.getString("lat");
            if(StringUtils.isBlank(lat)){
            	lat = LAT;
            }
            String lng = result.getString("lng");
            if(StringUtils.isBlank(lng)){
            	lng = LNG;
            }
            String province = result.getString("prov");
            String city = result.getString("city");
            address.setLat(lat);
            address.setLng(lng);
            address.setProvince(province);
            address.setCity(city);
            return address;
        }
        catch (Exception e){
            log.error("获取地理位置异常 {}", ip);
        }
        return address;
    }
    
}
